/**
 * 
 */
package com.cnhaimei.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @author Jin001.Wu@gmail.com <br>
 * @date 2011-7-5
 * 
 */
public class UDPSocket extends NetSocket implements Runnable {

	private static boolean Debug = true;

	private int port;
	private byte[] mReceiveBuf;// = new byte[4096];
	private byte[] mSendBuf;// = new byte[2048];
	private boolean isRunning;

	protected DatagramSocket mSocket;
	protected DatagramPacket mSendPacket;
	protected DatagramPacket mReceivePacket;

//	public UDPSocket(int port) {
//		this.port = port;
//	}
	
	public UDPSocket(int port, int receiverBufSize, int sendBufSize) {
		this.port = port;
		mReceiveBuf = new byte[receiverBufSize];
		mSendBuf = new byte[sendBufSize];
	}

	public void setPort(int pt) {
		port = pt;
	}
	
	public void run() {
//		setPriority(Thread.NORM_PRIORITY);

		try {
			mSocket = new DatagramSocket(port);
			mSendPacket = new DatagramPacket(mSendBuf, mSendBuf.length);
			mReceivePacket = new DatagramPacket(mReceiveBuf, mReceiveBuf.length);
			isRunning = true;
			onConnected(true);
			System.out.println("udp Client is created port:" + port);
		} catch (Exception e) {
			isRunning = false;
			onException(e);
			// 连接失败，请检查网络设置
		}

		try {
			while (isRunning) {
				isRunning = true;
				mReceivePacket = null;
				mReceivePacket = new DatagramPacket(mReceiveBuf, mReceiveBuf.length);
				mSocket.receive(mReceivePacket);
				onReceive(mReceivePacket);
			}
			isRunning = false;
		} catch (Exception e) {
			onException(e);
			isRunning = false;
			if (Debug) {
				e.printStackTrace();
				System.out.println("Exception e************ " + e.toString());
			}
		}
	}
	

	protected void onConnected(boolean isSuc) {

	}

	protected void onDisConnected() {

	}
	
	protected void onReceive(DatagramPacket mPacket) {
		
	}
	
	protected void onException(Exception e) {
		
	}
	
	public boolean isRun() {
		return isRunning;
	}

	public void stop() {
		// TODO Auto-generated method stub

	}

	public void start() {
		// TODO Auto-generated method stub

	}

	public int getType() {
		// TODO Auto-generated method stub
		return 0;
	}
	
	public void close() {
		if (mSocket != null) {
			try {
				mSocket.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
